<!doctype html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>chili3d</title>
    <link rel="icon" href="favicon.svg" />
    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <script src="./iconfont.js"></script>

    <script defer src="main.js"></script>
    <script>
      function jsonToBlob(json) {
        var textEncoder = new TextEncoder()
        var seen = new WeakSet()
        var buffer = new Uint8Array(1024 * 1024) // Start with 1MB buffer
        var position = 0
        var stringBuffer = ''

        function ensureCapacity(additionalBytes) {
          if (position + additionalBytes > buffer.length) {
            var newBuffer = new Uint8Array(
              Math.max(buffer.length * 2, position + additionalBytes),
            )
            newBuffer.set(buffer)
            buffer = newBuffer
          }
        }

        function writeToBuffer(str) {
          var encoded = textEncoder.encode(str)
          ensureCapacity(encoded.length)
          buffer.set(encoded, position)
          position += encoded.length
        }

        function flushStringBuffer() {
          if (stringBuffer.length > 0) {
            writeToBuffer(stringBuffer)
            stringBuffer = ''
          }
        }

        function processValue(value) {
          if (seen.has(value)) {
            throw new TypeError('Converting circular structure to JSON')
          }

          if (value && typeof value.toJSON === 'function') {
            value = value.toJSON()
          }

          if (typeof value === 'object' && value !== null) {
            seen.add(value)

            var isArray = Array.isArray(value)
            stringBuffer += isArray ? '[' : '{'

            var first = true
            for (var [key, val] of Object.entries(value)) {
              if (!first) stringBuffer += ','
              first = false

              if (!isArray) {
                stringBuffer += JSON.stringify(key) + ':'
              }

              processValue(val)
            }

            stringBuffer += isArray ? ']' : '}'
          } else if (
            typeof value === 'function' ||
            typeof value === 'undefined'
          ) {
            stringBuffer += 'null'
          } else {
            stringBuffer += JSON.stringify(value)
          }

          // Flush the string buffer if it gets too large
          if (stringBuffer.length > 1024) {
            flushStringBuffer()
          }
        }

        processValue(json)
        flushStringBuffer()

        return new Blob([buffer.subarray(0, position)])
      }
      function getFileFromUrl(url, fileName) {
        return new Promise((resolve, reject) => {
          var blob = null
          var xhr = new XMLHttpRequest()
          xhr.open('GET', url)
          xhr.responseType = 'blob'
          // 加载时处理
          xhr.onload = () => {
            // 获取返回结果
            blob = xhr.response
            var file = new File([blob], fileName, { type: blob.type })
            // 返回结果
            resolve(file)
          }
          xhr.onerror = e => {
            reject(e)
          }
          // 发送
          xhr.send()
        })
      }

      function exportGLTF(input) {
        return new Promise((resolve, reject) => {
          var gltfExporter = new GLTFExporter().setTextureUtils(
            window.WebGLTextureUtils,
          )
          var params = {
            trs: false,
            onlyVisible: true,
            binary: false,
            maxTextureSize: 4096,
          }
          var options = {
            trs: params.trs,
            onlyVisible: params.onlyVisible,
            binary: params.binary,
            maxTextureSize: params.maxTextureSize,
          }
          gltfExporter.parse(
            input,
            function (result) {
              resolve(result)
            },
            function (error) {
              reject()
              console.log('An error happened during parsing', error)
            },
            options,
          )
        })
      }

      function createURLFromString(text) {
        var blob = new Blob([text], { type: 'text/plain' })
        return URL.createObjectURL(blob)
      }
      function createURLFromJson(json) {
        var blob
        try {
          var text = JSON.stringify(json)
          var blob = new Blob([text], { type: 'text/plain' })
        } catch (e) {
          blob = jsonToBlob(json)
        }
        return URL.createObjectURL(blob)
      }
      function createURLFromArrayBuffer(arrayBuffer) {
        var blob = new Blob([arrayBuffer], { type: 'text/plain' })
        return URL.createObjectURL(blob)
      }
      function lineSegments2ToLine(line) {
        // 创建一个常规的 LineSegments 对象
        var tempLine = new window.THREE.LineSegments(
          line.geometry,
          line.material,
        )
        // 复制位置、旋转等属性
        tempLine.position.copy(line.position)
        tempLine.rotation.copy(line.rotation)
        tempLine.scale.copy(line.scale)
        console.log(line.geometry.toJSON(), line.material.toJSON())

        // 复制位置、旋转等属性
        // tempLine.position.copy(line.position)
        // tempLine.rotation.copy(line.rotation)
        // tempLine.scale.copy(line.scale)

        return tempLine
      }
      Promise.all([
        new Promise(resolve => {
          window.onload = function () {
            var timer = setInterval(() => {
              if (window.MyApp) {
                clearInterval(timer)

                window.MyApp.newDocument('Untitled').then(myDocument => {
                  resolve(myDocument)
                })
              }
            }, 100)
          }
        }),
        new Promise(resolve => {
          window.addEventListener(
            'message',
            ({ data }) => {
              resolve(data)
            },
            false,
          )
        }),
      ])
        .then(([myDocument, { url: modelURL, filename }]) => {
          return getFileFromUrl(
            modelURL,
            filename || modelURL.split('/').pop(),
          ).then(file => {
            return myDocument.application.dataExchange
              .import(myDocument, [file])
              .then(() => {
                var group = new window.THREEGroup()
                myDocument.visual.scene.children
                  .filter(
                    object => !object.isLight && object.type !== 'AxesHelper',
                  )
                  .forEach(child => {
                    child.traverse(c => {
                      // console.log(c, c.geometry)
                      if (c.isLineSegments2) {
                        // console.log(c)
                        // debugger
                        // console.log(c, c.geometry, c.toJSON(), c.fromJSON)
                        // console.log(c.toJSON())
                        // debugger
                        // var line = lineSegments2ToLine(c)
                        // console.log(c.parent)
                        // c.parent.add(line)
                        // c.parent.remove(c)
                        // console.log(c.parent)
                        // c.parent.add(c)
                      }
                    })
                    group.add(child)
                  })

                // console.log(group.toJSON())

                var json = group.toJSON()
                // var url = createURLFromString(JSON.stringify(json, null, 2))
                var url = createURLFromJson(json)
                window.parent.postMessage({ gltf: url })
                // return exportGLTF(
                //   myDocument.visual.scene.children.filter(
                //     object => !object.isLight && object.type !== 'AxesHelper',
                //   ),
                // ).then(content => {
                //   var url
                //   if (content instanceof ArrayBuffer) {
                //     url = createURLFromArrayBuffer(content)
                //   } else {
                //     url = createURLFromString(
                //       JSON.stringify(content, null, 2),
                //     )
                //     // var link = document.createElement('a')
                //     // link.style.display = 'none'
                //     // document.body.appendChild(link) // Firefox workaround, see #6594
                //     // link.href = url
                //     // link.download = 'scene.glb'
                //     // link.click()
                //   }
                //   window.parent.postMessage({ gltf: url })
                // })
              })
          })
        })
        .catch(e => {
          console.log(e)
          window.parent.postMessage({ error: e.message || e })
        })
    </script>
  </body>
</html>
